package com.demo.controller;

import com.demo.entity.Result;
import com.demo.entity.User;
import com.demo.util.CheckToken;
import com.demo.util.TokenUtils;
import com.demo.util.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {
    @PostMapping(value = "/login")
    public Result login(@RequestBody User user) {

        User dbUser = new User();
        if (user.getUsername().equals(dbUser.getUsername())) {

            if (user.getPassword().equals(dbUser.getPassword())) {
                //发放token令牌
                String token = TokenUtils.createToken(new TokenVo(user.getUsername(), user.getPassword()));
                log.info(user.getUsername() + "登录成功");
                return Result.success(token);
            } else {//密码错误
                log.info(user.getUsername() + "登录失败，密码错误");
                return Result.error("账号密码错误,或用户状态异常");
            }
        } else {
            log.info("登录失败，用户不存在");
            return Result.error("用户不存在");
        }
    }
    @GetMapping("/checkToken")
    public Result checkToken(HttpServletRequest request) {
        TokenVo tokenVo = new CheckToken().checkToken(request);
        if (tokenVo != null) {
            return Result.success(tokenVo);
        } else {
            return Result.error("token无效");
        }
    }
}
